package com.martin.fastframe.ui.danmu

import android.view.LayoutInflater
import android.widget.FrameLayout
import dev.utils.app.ScreenUtils
import java.util.concurrent.ConcurrentLinkedQueue

class DanMuModel(
    //弹幕父布局
    private val parent: FrameLayout,
    //弹幕行数
    private val lineCount: Int = 1,
) {

    //弹幕队列
    private val _queue = ConcurrentLinkedQueue<BaseDanMuItem>()

    //弹道是否可添加状态
    private val _lineStateList = arrayListOf<Boolean>().apply {
        for (i in 0 until lineCount) {
            add(true)
        }
    }

    //布局加载器
    private val _inflater by lazy {
        LayoutInflater.from(parent.context)
    }

    //屏幕宽度
    private val _screenWidth by lazy {
        ScreenUtils.getScreenWidth()
    }

    /**
     * 添加弹幕
     */
    fun offer(danMu: BaseDanMuItem) {
        _queue.offer(danMu)
        handleShow()
    }

    /**
     * 处理展示逻辑
     */
    private fun handleShow() {
        val index = _lineStateList.indexOf(true)
        //当前没有空闲弹道或弹幕队列为空,则不处理
        if (index == -1) {
            return
        }
        _queue.poll()?.let {
            //创建弹幕View
            val view = it.createView(parent, index)
            //添加到弹幕父布局中
            parent.addView(view)
            //设置弹幕view的位置
            view.x = _screenWidth.toFloat()
            val danMuMaxHeight = parent.height / lineCount
            view.y = (danMuMaxHeight * index) + ((danMuMaxHeight - view.height) / 2).toFloat()
            //设置弹道状态
            _lineStateList[index] = false
            //设置弹幕数据,并开始动画
            view.post {
                //绑定数据
                it.onBindData(view)
                //播放动画
                it.showAnimation(view) {
                    //设置弹道状态
                    _lineStateList[it.index] = true
                    //处理下一个弹幕展示逻辑
                    handleShow()
                }
            }
        }

    }
}